package common.dao.gremlin;


import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.util.TitanCleanup;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * Created by common on 7/15/2016.
 */
@Component
public class TitanGraphDao {
    /*
    Using java-gremlin library
    Write Gremlin natively in java
    En... Like Herbebate of SQL ???
     */

    private static final Logger logger = LoggerFactory.getLogger(TitanGraphDao.class);

    // 绝对路径
    public static final String PROPS_PATH = "gremlin_admin/titan-cassandra-es.properties";

    private TitanGraph graph;


    //@Inject
    public TitanGraphDao(){
        startDao();
    }

    public TitanGraphDao(String mode){
        if(mode.equalsIgnoreCase("debug")){
            startDao();
        }
    }

    @Override
    public void finalize() throws Throwable {
        super.finalize();
        stopDao();
    }

    private void stopDao(){
        if(!this.graph.isClosed()){
            this.graph.close();
        }
        logger.debug("[close titandb graph] titandb graph closed!");
    }


    private void startDao(){
        try {
            logger.info("Titan Properties Path: {}", PROPS_PATH);
            Configuration conf = new PropertiesConfiguration(PROPS_PATH);
            graph = TitanFactory.open(conf);
            logger.info("Titan graph loaded successfully.");
        } catch (ConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

    public void closeGraph(){
        this.graph.close();
    }

    public void openGraph(){
        startDao();
    }

    public void cleanUpGraph(){
        closeGraph();
        TitanCleanup.clear(this.graph);
        openGraph();
        logger.info("Clean Up Graph Succefully");
    }

    public TitanGraph getTitanGraph() {
        return this.graph;
    }


    /**************
     *
     * @param args
     */
    public static void main(String[] args){
        TitanGraphDao tgdao = new TitanGraphDao("debug");
        //GraphOfTheGodsFactory.load(tgdao.getTitanGraph());
        TitanGraph graph = tgdao.getTitanGraph();
        GraphTraversalSource g = graph.traversal();
        GraphTraversal ret = g.V();
        System.out.println(ret);
        System.out.println("load graph of gods successfully!");
    }
}
